package port

import (
	"fmt"
	"strconv"
	"strings"

	"gitee.com/liumou_site/gcs"
)

// DetectServiceByNmap 使用Nmap主动识别端口实际服务类型
func DetectServiceByNmap(host string, port int) (service, banner string, err error) {
	if !gcs.CheckCmd("nmap") {
		return "", "", fmt.Errorf("nmap命令未安装或未在PATH中")
	}

	shell := gcs.NewShell()
	shell.RunShell("nmap", "-sV", "-p", strconv.Itoa(port), host)
	if !shell.Result {
		return "", "", fmt.Errorf("nmap error: %v", shell.Strings)
	}
	output := shell.Strings
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		// 例：80/tcp   open  http    Apache httpd 2.4.41 ((Ubuntu))
		if strings.Contains(line, strconv.Itoa(port)+"/tcp") {
			fields := strings.Fields(line)
			if len(fields) >= 3 {
				service = fields[2]
				if len(fields) > 3 {
					banner = strings.Join(fields[3:], " ")
				}
			}
		}
	}
	return service, banner, nil
}
